package com.lgj.gateway.oauth;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.lgj.exception.BusinessException;
import com.lgj.gateway.config.IgnoreUrl;
import com.lgj.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;

@Slf4j
@Component
public class AuthenticationFilter implements GlobalFilter, Ordered{
    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private IgnoreUrl ignoreUrl;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String url = exchange.getRequest().getPath().toString();
        //过滤请求授权服务的接口
        if (ignoreUrl.getIgnoreUrlList().contains(url)){
            return chain.filter(exchange);
        }
        OAuth2AccessToken auth2AccessToken = tokenStore.readAccessToken(getToken(exchange));
        if (auth2AccessToken == null){
            throw new BusinessException(ResultCode.UN_AUTHORIZED);
        }
        OAuth2Authentication authentication = tokenStore.readAuthentication(auth2AccessToken.getValue());
        if (authentication == null){
            throw new BusinessException(ResultCode.UN_AUTHORIZED,"token无效");
        }
        return chain.filter(exchange);
    }

    /**
     * 获取token
     */
    private String getToken(ServerWebExchange exchange) {
        String tokenStr = exchange.getRequest().getHeaders().getFirst("Authorization");
        if (StringUtils.isBlank(tokenStr)) {
            return null;
        }
        String token = tokenStr.split(" ")[1];
        if (StringUtils.isBlank(token)) {
            return null;
        }
        return token;
    }


    @Override
    public int getOrder() {
        return -1;
    }
}
